package com.qk.interceptor;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1. 获取请求路径
        String uri = request.getRequestURI();
        //2. 判断是否是登录请求
        if (uri.contains("login")){


            return  true;
        }//3获取请求头中的token
        String jwt= request.getHeader("token");
        //4判断token是否存在
        if (jwt==null || jwt.isEmpty()){

            response.setStatus(401);
            return  false;
        }
        //5解析令牌，错返回401
        try {
            Claims claims = JwtUtils.parseToken(jwt);
            Integer userId = claims.get("id", Integer.class);
            CurrentUserHoler.setCurrentUser(userId);

//            JwtUtils.parseToken(jwt);
        }catch (Exception e){

            response.setStatus(401);
            return  false;
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        CurrentUserHoler.removeCurrentUser();
    }

}
